package top.cyuw.simplerpc.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import top.cyuw.simplerpc.config.RpcServiceConfig;
import top.cyuw.simplerpc.remoting.server.SimpleRpcServer;
import top.cyuw.simplerpc.spring.annotation.RpcService;

import java.net.InetSocketAddress;

/**
 * @author chen
 * @date 2023/3/14 22:23
 */
public class RpcServiceAnnotationPostProcessor implements BeanPostProcessor {

    private final SimpleRpcServer rpcServer;

    public RpcServiceAnnotationPostProcessor(SimpleRpcServer rpcServer) {
        this.rpcServer = rpcServer;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        RpcService rpcService = bean.getClass().getAnnotation(RpcService.class);
        if (rpcService != null) {
            rpcServer.start();
            RpcServiceConfig serviceConfig = RpcServiceConfig.builder()
                    .version(rpcService.version())
                    .group(rpcService.group())
                    .service(bean)
                    .build();
            InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9988);

            rpcServer.getServiceRegistry().registerService(serviceConfig, address);
        }
        return bean;
    }

}
